#include "evaluationEx.h"

void ex_show_stack(EX_LNODE *ptr){
    while(ptr != NULL){
        printf("%c", ptr->data);
        ptr = ptr->link;
    }
    printf("\n");
}
int ex_empty(EX_LNODE *ptr){
    if(ptr == NULL){
        return 1;
    }else{
        return 0;
    }
}
void ex_push(EX_LNODE **ptr, int item){
    EX_LNODE *p;
    if(ex_empty(*ptr)){
        p = malloc(sizeof(EX_LNODE));
        if(p != NULL){
            p->data = item;
            p->link = NULL;
            *ptr = p;
        }
    } else {
        p = malloc(sizeof(EX_LNODE));
        if(p != NULL){
            p->data = item;
            p->link = *ptr;
            *ptr = p;
        }
    }
}

void ex_pop(EX_LNODE **ptr, int *item){
    EX_LNODE *p1;
    p1 = *ptr;
    if(ex_empty(p1)){
        *item = '\0';
    } else{
        *item = p1->data;
        *ptr = p1->link;
        free(p1);
    }
}

int evaluate(char *postfix)
{
    EX_LNODE *stackb = NULL;
    char * pch;
    int op1,op2,result;
	
    pch = strtok (postfix," ");
    while (pch != NULL){
        int i = atoi(pch);
        if(i!=0){
            //printf("i = %d\n", i);
            ex_push(&stackb, i);
        } else{
            ex_pop(&stackb, &op1);
            ex_pop(&stackb, &op2);
            //printf ("%s\n",pch);
            switch(pch[0]){
				case '+':
					result = op2 + op1;
					break;
					
				case '-':
					result = op2 - op1;
					break;
					
				case '/':
					result = op2 / op1;
					break;
					
				case '*':
					result = op2 * op1;
					break;
					
				case '%':
					result = op2 % op1;
					break;
					
				default:
					printf("\nInvalid Operator");
					return 0;
			}
			ex_push(&stackb, result);
        }
        pch = strtok (NULL, " ");
    }
    ex_pop(&stackb, &result);
    return result;
}

